import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const http = axios.create({
	baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
	// timeout: 5000 // 请求超时时间
})

// 请求拦截器
http.interceptors.request.use(config => {
	const userStore = useUserStore()
	const token = userStore.userInfo?.token
	if (token) {
		config.headers.Authorization = `Bearer ${token}`
	}
	return config
}, error => {
	console.log(error)
	return Promise.reject(error)
})

// 响应拦截器
http.interceptors.response.use(response => {
	return response
}, error => {
	console.log(error);
	
	ElMessage({
		type: 'warning',
		message: error.response?.data.message || '网络请求失败，请稍后再试'
	})
	// 401 token失效

	if (error.response.status === 401) {
		useUserStore().logout()
	}

	return Promise.reject(error)
})

export default http